package com.schedule.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，底层逻辑就是AOP
 */

@Slf4j

//拦截添加以下注释的Controller
@ControllerAdvice(annotations = {Controller.class, RestController.class})

//由于需要返回json数据,添加该注释
@ResponseBody

public class GlobalExceptionHandler extends Exception{

    /**
     * 处理字段值重复的异常
     * @param ex
     * @return
     */
    //此异常处理器处理的异常类型为：SQLIntegrityConstraintViolationException.class
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public R<String> ExceptionHandler(SQLIntegrityConstraintViolationException ex){
        //日志
        log.error("出问题啦:{}",ex.getMessage());

        String msg = ex.getMessage();

        //若sql问题出现在 “字段名重复” ,将重复的字段找出并返回
        if (msg.contains("Duplicate entry")){
            String[] msg_split = msg.split(" ");
            String return_msg=msg_split[2]+"已存在";
            return R.error(return_msg);
        }

        return R.error("出现未知错误！");
    }

    @ExceptionHandler(value = CustomException.class)
    public R<String> ExceptionHandler(CustomException ex){
        //日志
        log.error("出现业务异常,{}",ex.getMessage());
        return R.error(ex.getMessage());
    }
}
